package com.github.permissiondog.cancanpandroid.ui.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.permissiondog.cancanpandroid.R;
import com.github.permissiondog.cancanpandroid.databinding.FragmentApplicationBinding;
import com.github.permissiondog.cancanpandroid.ui.adapter.ApplicantApplicationAdapter;
import com.github.permissiondog.cancanpandroid.util.Constants;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ApplicationFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ApplicationFragment extends Fragment {

    public ApplicationFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment ApplicationFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ApplicationFragment newInstance() {
        ApplicationFragment fragment = new ApplicationFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        FragmentApplicationBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_application, container, false);
        var linearLayoutManager = new LinearLayoutManager(getContext());
        binding.rvApplication.setLayoutManager(linearLayoutManager);
        var adapter = new ApplicantApplicationAdapter(inflater.getContext());
        binding.rvApplication.setAdapter(adapter);
        binding.btnCreateApplication.setOnClickListener(l -> {
            startActivity(new Intent(getContext(), SelectCourseActivity.class));
        });

        var intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_REFRESH_APPLICATIONS);
        getContext().registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                adapter.flush();
            }
        }, intentFilter);

        return binding.getRoot();
    }
}